package com.tal.warehouse.controller;

import com.tal.warehouse.dto.Stock;
import com.tal.warehouse.utils.EnvironmentUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Properties;

/**
 * @author max
 * @version 1.0.0
 * @ClassName WarehouseController.java
 * @Description TODO
 * @createTime 2021年03月27日 17:21:00
 */
@RestController
public class WarehouseController {

    private void printCurrentEnv() {
//        Resource app = new ClassPathResource("application.yml");
//        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
//        yamlPropertiesFactoryBean.setResources(app);
//        Properties properties = yamlPropertiesFactoryBean.getObject();
//        String activeEnv = properties.getProperty("spring.profiles.active");
        String activeEnv = EnvironmentUtils.searchByKey("spring.profiles.active");
        if (StringUtils.isEmpty(activeEnv)) {
            activeEnv = "prod";
        }
        System.out.println("当前环境: " + activeEnv);
    }

    /**
     * 查询对应 skuId 的库存状况
     *
     * @param skuId skuId
     * @return Stock 库存对象
     */
    @GetMapping("/stock")
    public Stock getStock(Long skuId) {
        printCurrentEnv();
        Stock stock = null;
        if (skuId == 1101L) {
            //模拟有库存商品
            stock = new Stock(1101L, "Apple iPhone 11 128GB 紫色", 32, "台");
            stock.setDescription("Apple 11 紫色版对应商品描述");
        } else if (skuId == 1102L) {
            //模拟无库存商品
            stock = new Stock(1101L, "Apple iPhone 11 256GB 白色", 0, "台");
            stock.setDescription("Apple 11 白色版对应商品描述");
        } else {
            //演示案例，暂不考虑无对应 skuId 的情况
        }
        return stock;
    }

    @PostMapping("/stock/{skuId}")
    public String updateStock(@PathVariable(value = "skuId") Long skuId) {
        return String.format("%s 库存更新成功", skuId);
    }

    @PostMapping("/stockDetails")
    public Stock update(@RequestBody Stock stock) {
        return stock;
    }


}
